﻿// ExecutableSettings.cs
// (c) 2011, Charles Lechasseur
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;

namespace LaunchWithParams
{
    //************************************************************************
    /// <summary>
    /// Wrapper for all settings specific to a particular executable that
    /// has been launched via LaunchWithParams, like last-used command-lines.
    /// </summary>
    //************************************************************************
    public sealed class ExecutableSettings
    {
        /// Path of registry key containing the data for executables.
        private const string SAVED_DATA_REG_PATH = @"Software\clechasseur\LaunchWithParams\SavedData\";

        /// Name of registry key used to store global, non-exe-specific data.
        private const string GLOBAL_DATA_EXE_NAME = "Global";

        /// Name of value storing most-recently used command-lines for the executable.
        private const string EXE_SETTING_MRU = "MRU";

        /// Name of value storing pinned command-lines for the executable.
        private const string EXE_SETTING_PINNED = "Pinned";

        /// Saves the path or name of the executable.
        private string executable;

        /// Stores the list of most-recently used command-lines for the executable.
        private List<CommandLineInfo> mruCommandLines = new List<CommandLineInfo>();

        /// Stores the list of pinned command-lines for the executable.
        private List<CommandLineInfo> pinnedCommandLines = new List<CommandLineInfo>();

        /// <summary>
        /// List of command-lines that were most recently used to launch
        /// the executable through LaunchWithParams.
        /// </summary>
        public CommandLineInfo[] MostRecentlyUsedCommandLines
        {
            get {
                return mruCommandLines.ToArray();
            }
        }

        /// <summary>
        /// List of pinned command-lines that are always displayed in the drop-down
        /// menu of LaunchWithParams for the executable.
        /// </summary>
        public CommandLineInfo[] PinnedCommandLines
        {
            get {
                return pinnedCommandLines.ToArray();
            }
        }

        //************************************************************************
        /// <summary>
        /// Constructor. Attempts to load global information, e.g. not linked to
        /// a specific executable. If no info is found, a new registry key is
        /// created for global info.
        /// </summary>
        //************************************************************************
        public ExecutableSettings()
            : this(GLOBAL_DATA_EXE_NAME)
        {
        }

        //************************************************************************
        /// <summary>
        /// Constructor. Attempts to load information for the specified executable
        /// from the registry. If no info is found, a new registry key for the
        /// executable is created.
        /// </summary>
        /// <param name="executable">Either a full path or just the filename of
        /// the executable. If a full path is found, we first search the
        /// registry for the path, and if it isn't found, we use the filename
        /// only. If a full path is passed and no info is found at all, the
        /// creation of the new registry key is determined by the
        /// <see cref="T:ApplicationSettings"/>.</param>
        //************************************************************************
        public ExecutableSettings(string executable)
        {
            // Save EXE info to be able to save data later.
            this.executable = executable;

            // Get registry key for the executable.
            using (RegistryKey exeKey = GetExeRegistryKey(executable)) {
                // Get lists for MRU and pinned command-lines and save them
                // in our properties.
                object aList = exeKey.GetValue(EXE_SETTING_MRU);
                if (aList != null && aList is string[]) {
                    mruCommandLines.AddRange(Array.ConvertAll((string[]) aList,
                        cs => new CommandLineInfo(cs, false)));
                }
                aList = exeKey.GetValue(EXE_SETTING_PINNED);
                if (aList != null && aList is string[]) {
                    pinnedCommandLines.AddRange(Array.ConvertAll((string[]) aList,
                        cs => new CommandLineInfo(cs, true)));
                }
            }
        }

        //************************************************************************
        /// <summary>
        /// Adds a command-line as the most-recently used command-lines. This
        /// might bump off the list the last command-line.
        /// </summary>
        /// <param name="cmdLine">Command-line to add to the MRU list.</param>
        //************************************************************************
        public void AddUsedCommandLine(string cmdLine)
        {
            // Try to find the command-line in the existing MRU list.
            // If we find it, remove it from its current spot. Then
            // add the command-line at the top of the list and trim
            // if needed.
            int existingIdx = mruCommandLines.FindIndex(cl => cl.CmdLine == cmdLine);
            if (existingIdx != -1) {
                mruCommandLines.RemoveAt(existingIdx);
            }
            mruCommandLines.Insert(0, new CommandLineInfo(cmdLine, false));
            if (mruCommandLines.Count > ApplicationSettings.SizeOfCommandLineLists) {
                mruCommandLines.RemoveAt(mruCommandLines.Count - 1);
            }
            Debug.Assert(mruCommandLines.Count <= ApplicationSettings.SizeOfCommandLineLists);
        }

        //************************************************************************
        /// <summary>
        /// Pins a new command-line for the executable.
        /// </summary>
        /// <param name="cmdLine">Command-line to pin.</param>
        //************************************************************************
        public void PinNewCommandLine(string cmdLine)
        {
            // Look for the command-line in the list. If it's not found, add it.
            // (There's currently no limit to this list.)
            if (pinnedCommandLines.FindIndex(cl => cl.CmdLine == cmdLine) == -1) {
                pinnedCommandLines.Add(new CommandLineInfo(cmdLine, true));
            }
        }

        //************************************************************************
        /// <summary>
        /// Unpins an existing command-line from the list of pinned command-lines
        /// for the executable.
        /// </summary>
        /// <param name="cmdLine">Command-line to unpin.</param>
        //************************************************************************
        public void UnpinCommandLine(string cmdLine)
        {
            // Look for the command-line and remove it from the list.
            int idx = pinnedCommandLines.FindIndex(cl => cl.CmdLine == cmdLine);
            if (idx != -1) {
                pinnedCommandLines.RemoveAt(idx);
            }
        }

        //************************************************************************
        /// <summary>
        /// Saves all data about the executable that is stored in this instance
        /// to the registry in the appropriate key.
        /// </summary>
        //************************************************************************
        public void SaveData()
        {
            using (RegistryKey key = GetExeRegistryKey(executable)) {
                key.SetValue(EXE_SETTING_MRU, Array.ConvertAll(MostRecentlyUsedCommandLines, cl => cl.CmdLine),
                    RegistryValueKind.MultiString);
                key.SetValue(EXE_SETTING_PINNED, Array.ConvertAll(PinnedCommandLines, cl => cl.CmdLine),
                    RegistryValueKind.MultiString);
            }
        }

        //************************************************************************
        /// <summary>
        /// Returns a registry key containing information about an executable,
        /// stored in the LaunchWithParams key.
        /// </summary>
        /// <param name="executable">Either the full path or just the filename
        /// of an executable.</param>
        /// <returns><c>RegistryKey</c> instance containing data for the
        /// executable. If it doesn't exist, one is created and returned.</returns>
        //************************************************************************
        private static RegistryKey GetExeRegistryKey(string executable)
        {
            // Check if a full path has been provided.
            RegistryKey key = null;
            bool hasFullPath = !String.IsNullOrEmpty(Path.GetDirectoryName(executable));
            if (hasFullPath) {
                // Try to find the exe using the full path. Replace any
                // backslash with forward slashes here since backslases
                // represents a separator in registry paths.
                key = Registry.CurrentUser.OpenSubKey(SAVED_DATA_REG_PATH + executable.Replace('\\', '/'), true);
            }

            // If we did not find info about the exe using full path, use
            // the filename only.
            if (key == null) {
                key = Registry.CurrentUser.OpenSubKey(SAVED_DATA_REG_PATH + Path.GetFileName(executable), true);
            }

            // If no info was found at all, we need to create a key.
            // How to do so depends on an application setting.
            if (key == null) {
                if (hasFullPath && ApplicationSettings.StoreExeSettingsWithFullPath) {
                    key = Registry.CurrentUser.CreateSubKey(SAVED_DATA_REG_PATH + executable.Replace('\\', '/'));
                } else {
                    key = Registry.CurrentUser.CreateSubKey(SAVED_DATA_REG_PATH + Path.GetFileName(executable));
                }
            }

            Debug.Assert(key != null);
            return key;
        }
    }
}
